/****************************
 * 预定义超级全局变量
 ***************************/
var $_SERVICE = this;
	$_SERVICE.defaultHeaders =  {};
	$_SERVICE.defaultHeaders['Authorization'] = '';

$(function($_SERVICE) {

		var $_Global = this;
		
		function wxOAuthLogin () {
			var self = this;
			// 微信 oAuth登陆第一阶段：获取code (code将用于第二阶段)
			
			var querys = [];
			var urlParams = {
				"appid": config.appid,
				"redirect_uri": encodeURIComponent(self.location.href),
				"response_type": "code",
				"scope": "snsapi_userinfo",
				"state": "STATE#wechat_redirect"
			};
			for (var p in urlParams) {
				querys.push(p + '=' + urlParams[p]);
			}
			var oauthUrl = config.oAuthUrl + '?' +querys.join('&');
//			console.log(oauthUrl);
			window.location.replace(oauthUrl);
//			return;
		}
		
		var toStateParams = window.location.search;

		// 未登录，执行微信 oauth 认证
		if (toStateParams.indexOf('code') < 0) {
			wxOAuthLogin ();
		} else {
            var dataType = $('body').attr('data-type');
            for (key in pageData) {
                if (key == dataType) {
                    pageData[key]($_Global);
                }
            }
			console.log('router finish!' + '  ' + getUrlParams('code'));
		}
		
    })

	function AuthService (par, callback) {
		ajax_post("http://qxapi.93liu.cn/cmopapi/rest/1.0/user/weChat", par, function (res) {
			if (!res.userToken || res.userToken == '') {
				
				var host = window.document.location.host;
				var path = window.document.location.pathname;

				if (path.indexOf('product') > 0 || path.indexOf('index') > 0 || path.indexOf('personal') > 0 || path.indexOf('test')) {
					return callback(res);
				} else {
					if (path.indexOf('bindNatural') < 0) {
						localStorage.setItem('toState', path);
						// console.log(host + path);
						window.location.href = "http://renren.93liu.cn/test/bindNatural.html";
					} else {
						return callback(res);
					}
				}

			} else {
				return callback(res);
			}
			// console.log(res);
		});
	}
	
// 页面数据
var pageData = {
    // ===============================================
    // 绑定页
    // ===============================================
    'login': function ($_Global) {

		AuthService (JSON.stringify({'code' : getUrlParams('code')}), function(res){
			console.log(res);
			var self = this;

			var u = navigator.userAgent;
			var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
			var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
			if(isiOS) {
				var style = document.getElementById("dynamic")
				style.innerHTML = '@media screen and (-webkit-min-device-pixel-ratio: 2) {.person_tel em,.person_now em,.person_tel input,.person_now input{ border: 0.5px solid #a0a0a0 } .person_tel input,.person_now input{border-left: transparent;} } @media screen and (-webkit-min-device-pixel-ratio: 3) {.person_tel em,.person_now em,.person_tel input,.person_now input{ border: 0.333px solid #a0a0a0 } .person_tel input,.person_now input{border-left: transparent;} }';
			}

			self.userNumberReg = /^1[23458]\d{9}$/;

			// console.log(res);
			$(".person_pic img").attr("src", res.headimgurl);
			$(".person_pic span").text(res.nickname);

			$_Global.valid = function () {

				self.userNumber = $("input[name='phoneNo']").val();

				var length = self.userNumber.length;
				if(length == 11) {
					if(!self.userNumberReg.test(self.userNumber)){
						$("#gx>i").html("请检查输入的手机号是否正确!");
						$("#gx").show();
						return;
					} else {
						$("#gx").hide();
					}
				}
			}

			$("#sub_btn2").click(function() {

				self.userNumber = $("input[name='phoneNo']").val();

				if(self.userNumber == '') {
					alert("手机号不能为空！");
					return false;
				}
				if(!self.userNumberReg.test(self.userNumber)) {
					alert("号码格式不正确，请重新输入!");
					return false;
				}

				$("#sub_btn2").unbind('click');
				$("#sub_btn2").css({ 'background': '#BFC3C7' });

				var data = JSON.stringify({'userName' : self.userNumber, "openid" : res.openid, "name" : res.nickname});

				ajax_post("http://qxapi.93liu.cn/cmopapi/rest/1.0/user/bind", data, function(res){
					if (res.code == '0000') {
						alert("恭喜, 绑定成功!");
						// console.log(localStorage.getItem('toState'));
						if (localStorage.getItem('toState')) {
							window.location.replace(localStorage.getItem('toState'));
						}
					}

					if (res.code == '0001') {
						alert(res.msg);
					}

				})

				return false;
			});

		});

    },
    
    // ===============================================
    // 产品页
    // ===============================================
    'product': function ($_Global) {
			
		AuthService (JSON.stringify({'code' : getUrlParams('code')}), function(res){
			console.log(res);
			console.log(res.userToken);
			
			var self = this
			
			var userToken;

			if (!res.userToken || res.userToken == '') {
				userToken = res.defaultToken;
			} else {
				userToken = res.userToken;
			}

			$_SERVICE.defaultHeaders['Authorization'] = userToken;
			var data = JSON.stringify({'userId': res.userId});
			// XMLHttpRequest.setRequestHeader('Authorization', res.userToken)
			ajax_post("http://qxapi.93liu.cn/cmopapi/rest/1.0/product/list", data, function(res) {

				console.log(res);
				var html = '';
				var icon = '';

				self.swiperCount = res.types.length;
				// for (var i=0, len=res.data.length; i < len; i++) {
				// 	html += '<a href="index.html?productCode='+ res.data[i].productCode +'" class="listItem" data-code="'+ res.data[i].productCode +'"><div class="img"><img src="'+ res.data[i].productLogoPic +'"></div><div class="listConter"><h3 class="title">'+ res.data[i].productSimpleName +'</h3><h3 class="price">￥20.00</h3><div class="info"><div><span class="money"><i class="iconfont icon-yongjin"></i>佣金￥'+ res.data[i].commi +'</span><span class="integral"></span></div><h4 class="number">已订购:5974笔</h4></div></div></a>';
				// 	// return html;
				// }

				for (var arr=0, arrlen=res.types.length; arr < arrlen; arr++) {
					for (var list=0, listlen=res.types[arr].products.length; list < listlen; list++ ){
						html += '<div class="payListItem typid'+ res.types[arr].typeId +'"><a href="index.html?productCode='+ res.types[arr].products[list].productCode +'" class="listItem"><div class="img"><img src="'+ res.types[arr].products[list].productLogoPic +'"></div><div class="listConter"><h3 class="title">'+ res.types[arr].products[list].productSimpleName +'</h3><h3 class="price">￥'+ res.types[arr].products[list].productPrice +'</h3><div class="info"><div><span class="money"><i class="iconfont icon-yongjin"></i>佣金￥'+ res.types[arr].products[list].commi +'</span><span class="integral"></span></div><h4 class="number">已订购:'+ res.types[arr].products[list].clickCount +'笔</h4></div></div></a></div>';
					}

					icon += '<div class="swiper-slide swiper-slide-next" data-num="'+ res.types[arr].typeId +'"><i class="iconfont '+ res.types[arr].title +'"></i><span>'+ res.types[arr].typeName +'</span></div>';
				}

				$(".payListCon").empty();
				$(".payListCon").html(html);
				$(".flowshopNav .swiper-wrapper").empty();
				$(".flowshopNav .swiper-wrapper").append(icon);
				$($(".flowshopNav .swiper-wrapper div")[0]).attr("class", "swiper-slide active swiper-slide-active");

				var initnum = $($(".flowshopNav .swiper-slide")[0]).data("num");
				$(".typid" + initnum ).css("display", "block");

				var swiper = new Swiper('.flowshopNav', {
					pagination: '.swiper-pagination',
					slidesPerView: 5,
					paginationClickable: true,
					spaceBetween: 0
				});

				var swiper = $(".flowshopNav .swiper-slide");
				var listItem = $(".payListItem");

				swiper.click(function(){
					var index = $(this).index();

					for(var i = 0; i < swiper.length; i++){
						if (i == index) {
							swiper.attr("class", "swiper-slide");
							$(swiper[i]).attr("class", "swiper-slide active");

							var num = $(swiper[i]).data("num")
							listItem.css("display", "none");
							$(".typid" + num).css("display", "block");
						}
					}

				})
				$(".header").css("display", "flex")
				$('#mask').css("display", "none")

			});
		});

    },
	// ===============================================
    // 微信支付
    // ===============================================
    'wepay': function ($_Global) {
			
		AuthService (JSON.stringify({'code' : getUrlParams('code')}), function(res){
			console.log(res);
			
			var self = this
			
			var userToken;
			var userId = res.userId;
			var openId = res.openid;

			if (!res.userToken || res.userToken == '') {
				userToken = res.defaultToken;
			} else {
				userToken = res.userToken;
			}
			console.log(userToken)
			$_SERVICE.defaultHeaders['Authorization'] = userToken;
			var data = JSON.stringify({'userId': res.userId, 'openId': res.openid});

			ajax_post("http://qxapi.93liu.cn/cmopapi/rest/1.0/porder/regPhone", data, function(res) {
				// console.log(res)
				if (res && res.code == '0000') {
					$("#phone").val(res.phone)
					refresh()
				}
			})

			function Popup() {
				var aBtn = null;
				var oPopup = null;
				var oPopupCon = null;
				var oPopupClose = null;
			};

			Popup.prototype.init = function (opt) {
				this.aBtn = document.querySelector(opt.aBtn);
				this.oPopup = document.querySelector(opt.oPopup);
				this.oPopupCon = document.querySelector(opt.oPopupCon);
				this.oPopupClose = document.querySelector(opt.oPopupClose);
				var This = this;

				this.aBtn.addEventListener("click", function () {

					var phoneNo = $("#phone").val();
					var productId = $("#productId1").val();
					var productId3 = $("#productId3").val();
					if ('' == phoneNo && opt.type != '0') {
						alert("请填写手机号码");
						return;
					} else if (!/^(13[0-9]|14[0-9]|15[0-9]|18[0-9])\d{8}$/i.test(phoneNo) && opt.type != '0') {
						alert("请填写正确的手机号码");
						return;
					}
					if (('' == productId && opt.type == '1')) {
						alert("请选择订购的流量");
						return;
					}

					if (productId3 == '' && opt.type == '2') {
						alert("请选择购买的话费");
						return;
					}

					This.oPopup.style.display = "block";
					var setH = This.oPopupCon.clientHeight;
					This.oPopupCon.style.marginTop = -(setH / 2) + "px";
					This.oPopupCon.classList.remove("zoomOutUp");
					This.oPopupCon.classList.add("zoomInDown");
				});

				// this.oPopupCon.addEventListener("click", function (ev) {
				// 	ev.stopPropagation();
				// 	This.oPopup.removeEventListener("click", function () { });
				// 	setTimeout(function () {
				// 		This.oPopup.addEventListener("click", function () {
				// 			This.oPopupCon.classList.remove("zoomInDown");
				// 			This.oPopupCon.classList.add("zoomOutUp");
				// 			setTimeout(function () {
				// 				This.oPopup.style.display = "none";
				// 			}, 1000);
				// 		})
				// 	}, 1050);
				// });

				// this.oPopupClose.addEventListener("click", function () {
				// 	This.oPopupCon.classList.remove("zoomInDown");
				// 	This.oPopupCon.classList.add("zoomOutUp");
				// 	setTimeout(function () {
				// 		This.oPopup.style.display = "none";
				// 	}, 1000);
				// });
			};

			var p1 = new Popup();
			p1.init({
				aBtn: ".icon-flowPacket",
				oPopup: ".kindly",
				oPopupCon: ".kindlyCon",
				oPopupClose: ".kindlyBtn",
				type: "0"
			});

			var p2 = new Popup();
			p2.init({
				aBtn: ".purchaseBtn1",
				oPopup: ".province",
				oPopupCon: ".provinceCon",
				oPopupClose: ".provinceBtn",
				type: "1"

			});

			var p3 = new Popup();
			p3.init({
				aBtn: ".purchaseBtn2",
				oPopup: ".domestic",
				oPopupCon: ".domesticCon",
				oPopupClose: ".domesticBtn",
				type: "1"
			});

			$("#phone").keyup(function(){
				refresh();
			})

			function refresh() {
				
				var phone = $("#phone").val();
				var num = $("#phone").val().length;
				var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(14[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
				if (num == 11) {
					if (!myreg.test(phone)) {
						alert("输入的号码格式有误!")
						return false;
					} else {

						var data = JSON.stringify({'phoneNo': phone});

						$_SERVICE.defaultHeaders['Authorization'] = userToken;
						ajax_post("http://qxapi.93liu.cn/cmopapi/rest/1.0/product/backward", data, function(res) {
							console.log(res);

							if (res && res.code == '0000') {

								// render
								$("#flowPacket").empty();
								$(".flowPrice").empty();
								var html = '';
								var qg = '';
								var sn = '';
								
								for (var p in res.data) {

									for (var i=0,len=res.data[p].length; i<len; i++) {
										if (res.data[p][i]['regionNo'] == 'QG') {
											qg += '<div class="flowPriceCon flowPriceCon2" data-package="'+ p +'"><div class="left"><div class="PriceConTop"><h3 class="price price2">'+ res.data[p][i]['productPrice'] +'元</h3><span class="region2">国内</span><div class="hotMsg integral1"></div></div><h4 class="introduce">'+ res.data[p][i]['productDes'] +'</h4></div><div class="purchaseBtn1" data-code="'+ res.data[p][i]['productCode'] +'" data-name="'+ res.data[p][i]['productName'] +'" data-count="'+ res.data[p][i]['productPrice'] +'" data-region="'+ res.data[p][i]['regionNo'] +'" data-productauth="'+ res.data[p][i]['productToken'] +'">购买</div></div>'; 
										} else {
											sn += '<div class="flowPriceCon flowPriceCon1" data-package="'+ p +'"><div class="left"><div class="PriceConTop"><h3 class="price price1">'+ res.data[p][i]['productPrice'] +'元</h3><span class="region1">省内</span><div class="hotMsg integral1"></div><i class="iconfont icon-hui"></i></div><h4 class="introduce">'+ res.data[p][i]['productDes'] +'</h4></div><div class="purchaseBtn1" data-code="'+ res.data[p][i]['productCode'] +'" data-name="'+ res.data[p][i]['productName'] +'" data-count="'+ res.data[p][i]['productPrice'] +'" data-region="'+ res.data[p][i]['regionNo'] +'" data-productauth="'+ res.data[p][i]['productToken'] +'">购买</div></div>';
										}
									}

									html += '<li class="item"><span>'+ p +'</span></li>'
								}

								$("#flowPacket").html(html);
								$(".flowPrice").html(sn + qg);
								$("#flowPacket li:first-child").addClass("active");
								$(".flowPriceCon").css("display", "none");

								function who(){
									var who = $("#flowPacket li.item.active").text();
									for (var i=0,len=$(".flowPriceCon").length; i<len; i++) {
										if ($($(".flowPriceCon")[i]).data("package") == who) {
											$($(".flowPriceCon")[i]).css("display", "flex");
										}
									}
								}; who();

								$("#flowPacket li").click(function(){
									$(this).addClass("active").siblings("li").removeClass("active");
									$(".flowPriceCon").css("display", "none");
									who();
								})

								$(".purchaseBtn1").click(function(){

									$("#proId1").text($(this).data("code"));
									$("#phone1").text(phone);
									$("#pname1").text($(this).data("name"));
									$("#pprice1").text($(this).data("count"));
									$("#productAuth").text($(this).data("productauth"))

									if ($(this).data("region") == 'QG') {
										$(".introduce").text("国内流量 立即生效 月底失效 适用于2/3/4G用户")
									} else {
										$(".introduce").text("省内流量 立即生效 月底失效 适用于2/3/4G用户")
									}

									$(".province").css("display", "block");
									var setH = $(".provinceCon").height();
									$(".provinceCon").css("margin-top", -(setH / 2) + "px");
									$(".provinceCon").removeClass("zoomOutUp");
									$(".provinceCon").addClass("zoomInDown");
									
								})

								$(".provinceBtn").click(function(){
									$(".provinceCon").removeClass("zoomInDown")
									$(".provinceCon").addClass("zoomOutUp");
									setTimeout(function(){
										$(".province").css("display", "none")
									}, 1000);
								})

								$('#pay1').on('click', function () {
									var phoneNo = $("#phone").val();
									var productCode = $("#proId1").text();
									var productauth = $("#productAuth").text();
									if ('' == phoneNo) {
										alert("请填写手机号码");
										return;
									} else if (!/^(13[0-9]|14[0-9]|15[0-9]|18[0-9])\d{8}$/i.test(phoneNo)) {
										alert("请填写正确的手机号码");
										return;
									}
									
									var data = JSON.stringify({"userId": userId, "productCode": productCode, "phoneNo": phoneNo, "openId": openId})
									$.ajax({
										type: "POST", url: "http://qxapi.93liu.cn/cmopapi/rest/1.0/porder/order",
										data: data,	dataType: "json", contentType: "application/json",
										headers: {"Authorization": userToken, "productAuth": productauth},
										success: function (res) {
											// console.log(res)
											if (res.prepayInfo && res.prepayInfo != '') {
												var prepay = JSON.parse(res.prepayInfo)
												// console.log(prepay);
												callpay(prepay);
											}
											
										}
									});

									function callpay(sJson){
										var appid = sJson.appId;
										var timeStamp = sJson.timeStamp;
										var nonceStr = sJson.nonceStr;
										var packageValue = sJson.package;
										var paySign = sJson.sign;
										var out_trade_no = sJson.out_trade_no;
										var signType = sJson.signType;
										var flag = 0;
										WeixinJSBridge.invoke('getBrandWCPayRequest',{
											"appId" : appid,"timeStamp" : timeStamp, "nonceStr" : nonceStr, "package" : packageValue,"signType" : "MD5", "paySign" : paySign
										},function(res){
											WeixinJSBridge.log(res.err_msg);
											if(res.err_msg == "get_brand_wcpay_request:ok"){  
												flag = 1;
											}else if(res.err_msg == "get_brand_wcpay_request:cancel"){  
												flag = 2;
											}else{  
											var tip = res.err_code + res.err_desc + res.err_msg;
											flag = 3;
											}  
										})
									}


								});

							}

						});
					}
				}
			}


			$(".pay_close_btn").click(function () {
				$('.apply_out').css('display', 'none');
				return false;
			});

		});

    },
	// ===============================================
    // 详情页
    // ===============================================
    'index': function ($_Global) {
		
		var isAuth = false;

		AuthService (JSON.stringify({'code' : getUrlParams('code')}), function(res){

			var self = this;
			self.res = res;

			console.log(res);
			isAuth = true; 
			productAuth = '';
			product = getUrlParams('productCode');

			var userToken;

			if (!res.userToken || res.userToken == '') {
				userToken = res.defaultToken;
			} else {
				userToken = res.userToken;
			}

			$_SERVICE.defaultHeaders['Authorization'] = userToken;
			var data = JSON.stringify({'productCode': product});
			// XMLHttpRequest.setRequestHeader('Authorization', res.userToken)

			ajax_post("http://qxapi.93liu.cn/cmopapi/rest/1.0/product/find", data, function(res) {
				console.log(res);
				self.productAuth = res.productToken;

				$(".zoomInLeft").text(res.productDes);
				$(".jiayou_title h3").text(res.productSimpleName);
				$(".trriffUnit").text(res.tariffUnit);
				$(".productPrice").text(res.productPrice);
				$(".commi").text(res.commi);
				$(".ywgz").text(res.productDes);
				$(".gwts").text(res.productFeature);
				$(".jiayou_img img").attr("src", res.productDetailPic);


				$(".icon-qrcode").click(function(){
					$(".imgtitle").attr("src", self.res.headimgurl);
					$(".prdpic").attr("src", res.productDetailPic);
					$(".prdqrname").text(res.productName);
					$(".qrprdprice span").text(res.productPrice);

					var host = window.document.location.host;
					var path = window.document.location.pathname;
					var productCode = res.productCode;
					var userId = self.res.userId;
					var openid = self.res.openid;

					var url = "http://" + host + path + '?productCode=' + productCode + '&userId=' + userId + '&openId=' + openid;

					$.ajax({
						type:"post",
						url:"http://qxapi.93liu.cn/cmopapi/rest/1.0/util/twocode",
						async:true,
						dataType: "text",
						contentType: "application/json",
						beforeSend: function(request) {
							request.setRequestHeader("Authorization", userToken);
						},
						data: JSON.stringify({"url": url}),
						success: function(res){
							var src = "data:image/jpg;base64," + res;
							$(".qrcodeimg").attr("src", src);
						},
						error: function(res){
							console.log(res)
						}
					});

					$(".qrmask").css("display", "block");
				})

				$(".cha").click(function(){
					$(".qrmask").css("display", "none");
				})




			});

			// var shanfu = document.querySelector("#shanfu");
			// 	shanfu.addEventListener("touchstart", function () {
			// 		this.classList.add("rubberBand");
			// 	});
			// 	shanfu.addEventListener("touchend", function () {
			// 		setTimeout(function () {
			// 			shanfu.classList.remove("rubberBand");
			// 		}, 1000)
			// 	});

			// 	var tel = document.querySelector("#tel");
			// 	var wrap = document.querySelector(".wrap");

			// 	var ua = navigator.userAgent.toLowerCase();
			// 	if (!/iphone|ipad|ipod/.test(ua)) {
			// 		tel.onfocus = function () {
			// 			wrap.scrollTop = 300;
			// 		};
			// 		tel.onblur = function () {
			// 			wrap.scrollTop = 0;
			// 		}
			// 	}

			// function Popup() {
			// 	var aBtn = null;
			// 	var oPopup = null;
			// 	var oPopupCon = null;
			// 	var oPopupClose = null;
			// }

			// Popup.prototype.init = function (opt) {
			// 	this.aBtn = document.querySelector(opt.id);
			// 	this.oPopup = document.querySelector(".juboon_popup");
			// 	this.oPopupCon = document.querySelector(".juboon_popup_con");
			// 	this.oPopupClose = document.querySelector(".juboon_popup_close");

			// 	var This = this;

			// 	this.aBtn.addEventListener("click", function () {
					

			// 	});
			// 	this.oPopupClose.addEventListener("click", function () {
			// 		This.oPopupCon.classList.remove("zoomInDown");
			// 		This.oPopupCon.classList.add("zoomOutUp");
			// 		setTimeout(function () {
			// 			This.oPopup.style.display = "none";
			// 		}, 1000);
			// 	});
			// }

			// var p1 = new Popup();
			// p1.init({id: "#button", commType: "0"});
			// var p2 = new Popup();
			// p2.init({id: ".jiayoubtn_b", commType: "1"});
			// var p3 = new Popup();
			// p3.init({id: "#button",	commType: "0"});

			// var iconQR = document.querySelector(".iconQR");
			// var QR_popup = document.querySelector(".QR_popup");
			// var QRCon = document.querySelector(".QR_popup_con");
			// var QRClose = document.querySelector(".QR_popup_close");
			// iconQR.addEventListener("click", function () {
			// 	QR_popup.style.display = "block";
			// 	QRCon.classList.remove("zoomOutUp");
			// 	QRCon.classList.add("zoomInDown");
			// })
			// QRClose.addEventListener("click", function () {
			// 	QRCon.classList.remove("zoomInDown");
			// 	QRCon.classList.add("zoomOutUp");
			// 	setTimeout(function () {
			// 		QR_popup.style.display = "none";
			// 	}, 1000);
			// })


			$("#button").click(function(){

				if (!res.userToken || res.userToken == '') {
					var toMobile = $("#tel").val();
					var re = /^1[23458]\d{9}$/;
					
					if (toMobile == '') {
						$("#note").html("请输入推荐的手机号码!");
						$(".juboon_popup").css("display", "block")
						$(".juboon_popup_con").removeClass("zoomOutUp");
						$(".juboon_popup_con").addClass("zoomInDown");
						return;
					}

					if (!re.test(toMobile)) {
						$("#note").html("号码格式不正确，请重新输入!");
						$(".juboon_popup").css("display", "block")
						$(".juboon_popup_con").removeClass("zoomOutUp");
						$(".juboon_popup_con").addClass("zoomInDown");
						return;
					}

					$("#note").html("请先绑定手机号码在推荐!");
					$(".juboon_popup").css("display", "block")
					$(".juboon_popup_con").removeClass("zoomOutUp");
					$(".juboon_popup_con").addClass("zoomInDown");
					return false;


				} else {
					var toMobile = $("#tel").val();
					var re = /^1[23458]\d{9}$/;
					
					if (toMobile == '') {
						$("#note").html("请输入推荐的手机号码!");
						$(".juboon_popup").css("display", "block")
						$(".juboon_popup_con").removeClass("zoomOutUp");
						$(".juboon_popup_con").addClass("zoomInDown");
						return;
					}

					if (!re.test(toMobile)) {
						$("#note").html("号码格式不正确，请重新输入!");
						$(".juboon_popup").css("display", "block")
						$(".juboon_popup_con").removeClass("zoomOutUp");
						$(".juboon_popup_con").addClass("zoomInDown");
						return;
					}

					// getUrlParams()

					var data = JSON.stringify({"userId": res.userId, "productCode": product, "phoneNo": $("#tel").val(), "openId": res.openid})
					console.log(data)
					// console.log(res.userToken + '   ' + self.productAuth);
					$.ajax({
						type: "POST", url: "http://qxapi.93liu.cn/cmopapi/rest/1.0/porder/order",
						data: data,	dataType: "json", contentType: "application/json",
						headers: {"Authorization": userToken, "productAuth": self.productAuth},
						success: function (res) {
							console.log(res);

							if (res.code && res.code == '0000') {
								$("#tel").val("");
								$("#note").html('推荐' + res.msg);
								$(".juboon_popup").css("display", "block")
								$(".juboon_popup_con").removeClass("zoomOutUp");
								$(".juboon_popup_con").addClass("zoomInDown");
							}
							if (res.code && res.code == '0001') {
								$("#note").html(res.msg);
								$(".juboon_popup").css("display", "block")
								$(".juboon_popup_con").removeClass("zoomOutUp");
								$(".juboon_popup_con").addClass("zoomInDown");
							}
							if (res.code && res.code == '0002') {
								$("#note").html('推荐失败');
								$(".juboon_popup").css("display", "block")
								$(".juboon_popup_con").removeClass("zoomOutUp");
								$(".juboon_popup_con").addClass("zoomInDown");
							}
							
						}, error: function() {
							$("#note").html('网络错误，请重试');
							$(".juboon_popup").css("display", "block")
							$(".juboon_popup_con").removeClass("zoomOutUp");
							$(".juboon_popup_con").addClass("zoomInDown");
						}
					});
				}
			});

			$(".juboon_popup_close").click(function(){
				$(".juboon_popup_con").removeClass("zoomInDown")
				$(".juboon_popup_con").addClass("zoomOutUp");
				setTimeout(function(){
					$(".juboon_popup").css("display", "none")
				}, 1000);
			})

		});
    },
    // ===============================================
    // 个人中心
    // ===============================================
    'personal': function ($_Global) {
		AuthService (JSON.stringify({'code' : getUrlParams('code')}), function(res){
			console.log(res);

			$(".face img").attr("src", res.headimgurl);
			$(".name").text(res.nickname);


		});
    },
    // ===============================================
    // 我的佣金
    // ===============================================
    'prize': function ($_Global) {
		AuthService (JSON.stringify({'code' : getUrlParams('code')}), function(res){
			console.log(res);

			var date = new Date;
			var month = date.getFullYear() + ((date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1));
			console.log(month)

			$_SERVICE.defaultHeaders['Authorization'] = res.userToken;
			var data = JSON.stringify({'userId': res.userId, 'month': month});

			ajax_post("http://qxapi.93liu.cn/cmopapi/rest/1.0/commi/monthCommi", data, function(res){
				// console.log(res);

				if (res.code && res.code == '0000') {
					var commi = res.commi;
					commi = commi.toFixed(1)
					$('.month span').text(commi);
					$(".commi").text(commi)
				}

			})			

		});
    },
	// ===============================================
    // 佣金明细查询
    // ===============================================
	'commission': function ($_Global) {
		AuthService (JSON.stringify({'code' : getUrlParams('code')}), function(res){
			console.log(res);

			function listInit (beginDate, endDate) {
				$_SERVICE.defaultHeaders['Authorization'] = res.userToken;
				var data = JSON.stringify({"userId": res.userId, "beginDate" : beginDate, "endDate": endDate});

				ajax_post("http://qxapi.93liu.cn/cmopapi/rest/1.0/commi/commiDetail", data, function(res){
					console.log(res);

					if (res.code && res.code == '0000') {

						if(res.data.length > 0) {
							$(".data_empty").css("display", "none")
						}

						var html = '';
						// var html_suc = '';
						// var html_err = '';
						// var html_dea = '';
						for (var i=0, len=res.data.length; i < len; i++) {
							html += '<tr><td>'+ res.data[i].phoneNo +'</td><td>'+ res.data[i].productName +'</td><td>'+ res.data[i].commi +'</td><td>'+ res.data[i].openDate +'</td></tr>';

							// switch (res.data[i].stateDesc) {
							// 	case '开通成功': 
							// 		html_suc += '<li><div class="order_list_l"><span>'+ res.data[i].phoneNo +'</span><em>'+ res.data[i].productName +'</em></div><div class="order_list_c">'+ res.data[i].commi +'元</div><div class="order_list_r">'+ res.data[i].openDate +'</div></li>';
							// 	break;
							// 	case '开通失败': 
							// 		html_err += '<li><div class="order_list_l"><span>'+ res.data[i].phoneNo +'</span><em>'+ res.data[i].productName +'</em></div><div class="order_list_c">'+ res.data[i].commi +'元</div><div class="order_list_r">'+ res.data[i].openDate +'</div></li>';
							// 	break;
							// 	case '处理中': 
							// 		html_dea += '<li><div class="order_list_l"><span>'+ res.data[i].phoneNo +'</span><em>'+ res.data[i].productName +'</em></div><div class="order_list_c">'+ res.data[i].commi +'元</div><div class="order_list_r">'+ res.data[i].openDate +'</div></li>';
							// 	break;
							// }
						}
					}

					$(".commissionList").empty();
					$(".commissionList").html(html);

					// $(".all").click(function(){
					// 	$(".order_list").empty();
					// 	$(".order_list").html(html);
					// })
					// $(".state_suc").click(function(){
					// 		$(".order_list").empty();
					// 		$(".order_list").html(html_suc);
					// })
					// $(".state_err").click(function(){
					// 	$(".order_list").empty();
					// 	$(".order_list").html(html_err);
					// })
					// $(".state_dea").click(function(){
					// 	$(".order_list").empty();
					// 	$(".order_list").html(html_dea);
					// })
				})
			};	listInit('', '');

			$("#search").click(function(){
				// $(".order_nav a").removeClass("active");
				// $(".order_nav .all").addClass("active");

				var start = $("input[name='_query.startTime']").val().toString().split("-").join("");
				var end = $("input[name='_query.endTime']").val().toString().split("-").join("");

				if (start > end) {
					alert("起始时间不能大于结束时间")
				} else {
					listInit(start, end);
				}

				// console.log(start)
				// console.log(end)
			})
		});
	},
	// ===============================================
    // 推荐记录查询
    // ===============================================
    'order': function ($_Global) {

		AuthService (JSON.stringify({'code' : getUrlParams('code')}), function(res){
			console.log(res);
			var self = this;

			function init(phoneNo, productName){
				$_SERVICE.defaultHeaders['Authorization'] = res.userToken;
				var data = JSON.stringify({"userId": res.userId, "productClass": '0', "phoneNo": phoneNo, "productName": productName, "beginDate": $("#begin_time").val(), "endDate": $("#end_time").val()});

				ajax_post("http://qxapi.93liu.cn/cmopapi/rest/1.0/porder/detail", data, function(res){
					console.log(res)

					if (res.code && res.code == '0000') {

						var html = '';
						var html_suc = '';
						var html_err = '';
						// var html_ord = '';
						var html_dea = '';


						if (res.data.length > 0) {
							$(".data_empty").css("display", "none")
						}

						for (var i=0, len=res.data.length; i < len; i++) {

							if (res.data[i].lastState == '02') {
								res.data[i].stateDesc = '开通失败'
							}

							html += '<li><div class="order_list_l"><span>'+ res.data[i].phoneNo +'</span><em>'+ res.data[i].productName +'</em></div><div class="order_list_c">'+ res.data[i].productPrice +'元</div><div class="order_list_r">'+ res.data[i].stateDesc +'</div><div class="order_list_rr">'+ res.data[i].registerDate +'</div></li>';

							switch (res.data[i].lastState) {
								case '03': 
									html_suc += '<li><div class="order_list_l"><span>'+ res.data[i].phoneNo +'</span><em>'+ res.data[i].productName +'</em></div><div class="order_list_c">'+ res.data[i].productPrice +'元</div><div class="order_list_r">'+ res.data[i].stateDesc +'</div><div class="order_list_rr">'+ res.data[i].registerDate +'</div></li>';
								break;
								case '02': 
									html_err += '<li><div class="order_list_l"><span>'+ res.data[i].phoneNo +'</span><em>'+ res.data[i].productName +'</em></div><div class="order_list_c">'+ res.data[i].productPrice +'元</div><div class="order_list_r">'+ res.data[i].stateDesc +'</div><div class="order_list_rr">'+ res.data[i].registerDate +'</div></li>';
								break;
								// case '订购中': 
								// 	html_ord += '<li><div class="order_list_l"><span>'+ res.data[i].phoneNo +'</span><em>'+ res.data[i].productName +'</em></div><div class="order_list_c">'+ res.data[i].productPrice +'元</div><div class="order_list_r">'+ res.data[i].stateDesc +'</div></li>';
								// break;
								case '01': 
									html_dea += '<li><div class="order_list_l"><span>'+ res.data[i].phoneNo +'</span><em>'+ res.data[i].productName +'</em></div><div class="order_list_c">'+ res.data[i].productPrice +'元</div><div class="order_list_r">'+ res.data[i].stateDesc +'</div><div class="order_list_rr">'+ res.data[i].registerDate +'</div></li>';
								break;
							}
						}

						$(".order_list").empty();
						$(".order_list").html(html);

						$(".all").click(function(){
							$(".order_list").empty();
							$(".order_list").html(html);
						})
						$(".state_suc").click(function(){
							$(".order_list").empty();
							$(".order_list").html(html_suc);
						})
						$(".state_err").click(function(){
							$(".order_list").empty();
							$(".order_list").html(html_err);
						})
						// $(".state_ord").click(function(){
						// 	$(".order_list").empty();
						// 	$(".order_list").html(html_ord);
						// })
						$(".state_dea").click(function(){
							$(".order_list").empty();
							$(".order_list").html(html_dea);
						})
					}
				})
			}; init('', '');


			$("#search").click(function(){
				// var phoneNo = '';
				// var productName = '';

				var qureyType = $("#query").val();
				var re = /^1[23458]\d{9}$/;

				if (qureyType.length == '11' && re.test(qureyType)) {
					init(qureyType, '');
				} else {
					init('', qureyType);
				}
			})



		});

    },
	// ===============================================
    // 微信支付查询
    // ===============================================
	'orderAfter': function () {
		AuthService (JSON.stringify({'code' : getUrlParams('code')}), function(res){
			console.log(res);
			var self = this;

			function init(phoneNo, productName){
				$_SERVICE.defaultHeaders['Authorization'] = res.userToken;
				var data = JSON.stringify({"userId": res.userId, "productClass": '1', "phoneNo": phoneNo, "productName": productName, "beginDate": $("#begin_time").val(), "endDate": $("#end_time").val()});

				ajax_post("http://qxapi.93liu.cn/cmopapi/rest/1.0/porder/detail", data, function(res){
					console.log(res)

					if (res.code && res.code == '0000') {

						var html = '';
						var html_suc = '';
						var html_err = '';
						// var html_ord = '';
						var html_dea = '';
						for (var i=0, len=res.data.length; i < len; i++) {

							if (res.data[i].lastState == '01') {
								res.data[i].stateDesc = '受理中'
							}


							html += '<li><div class="order_list_l"><span>'+ res.data[i].phoneNo +'</span><em>'+ res.data[i].productName +'</em></div><div class="order_list_c">'+ res.data[i].productPrice +'元</div><div class="order_list_r">'+ res.data[i].stateDesc +'</div><div class="order_list_rr">'+ res.data[i].registerDate +'</div></li>';

							switch (res.data[i].lastState) {
								case '03': 
									html_suc += '<li><div class="order_list_l"><span>'+ res.data[i].phoneNo +'</span><em>'+ res.data[i].productName +'</em></div><div class="order_list_c">'+ res.data[i].productPrice +'元</div><div class="order_list_r">'+ res.data[i].stateDesc +'</div><div class="order_list_rr">'+ res.data[i].registerDate +'</div></li>';
								break;
								case '02': 
									html_err += '<li><div class="order_list_l"><span>'+ res.data[i].phoneNo +'</span><em>'+ res.data[i].productName +'</em></div><div class="order_list_c">'+ res.data[i].productPrice +'元</div><div class="order_list_r">'+ res.data[i].stateDesc +'</div><div class="order_list_rr">'+ res.data[i].registerDate +'</div></li>';
								break;
								// case '订购中': 
								// 	html_ord += '<li><div class="order_list_l"><span>'+ res.data[i].phoneNo +'</span><em>'+ res.data[i].productName +'</em></div><div class="order_list_c">'+ res.data[i].productPrice +'元</div><div class="order_list_r">'+ res.data[i].stateDesc +'</div></li>';
								// break;
								case '01': 
									html_dea += '<li><div class="order_list_l"><span>'+ res.data[i].phoneNo +'</span><em>'+ res.data[i].productName +'</em></div><div class="order_list_c">'+ res.data[i].productPrice +'元</div><div class="order_list_r">'+ res.data[i].stateDesc +'</div><div class="order_list_rr">'+ res.data[i].registerDate +'</div></li>';
								break;
							}
						}

						$(".order_list").empty();
						$(".order_list").html(html);

						$(".all").click(function(){
							$(".order_list").empty();
							$(".order_list").html(html);
						})
						$(".state_suc").click(function(){
							$(".order_list").empty();
							$(".order_list").html(html_suc);
						})
						$(".state_err").click(function(){
							$(".order_list").empty();
							$(".order_list").html(html_err);
						})
						// $(".state_ord").click(function(){
						// 	$(".order_list").empty();
						// 	$(".order_list").html(html_ord);
						// })
						$(".state_dea").click(function(){
							$(".order_list").empty();
							$(".order_list").html(html_dea);
						})
					}
				})
			}; init('', '');


			$("#search").click(function(){
				// var phoneNo = '';
				// var productName = '';

				var qureyType = $("#query").val();
				var re = /^1[23458]\d{9}$/;

				if (qureyType.length == '11' && re.test(qureyType)) {
					init(qureyType, '');
				} else {
					init('', qureyType);
				}
			})



		});
	}
}